﻿
using DevelopAssistant.Service;
using ICSharpCode.WinFormsUI.Controls;
using ICSharpCode.WinFormsUI.Controls.NTimeLine;
using ICSharpCode.WinFormsUI.Docking;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace DevelopAssistant.Core.Contents
{
    public partial class HomeContent : DockContent
    {
        MainForm mainForm = null;

        private bool IsTodoPromped = false;

        List<TodoManager.TodoDTO> todoList = null;

        TodoManager.ITodoService serviece = new TodoManager.TodoServiceImpl();

        System.Windows.Forms.Timer ScheduleTimer = null;

        public HomeContent(MainForm main)
        {
            mainForm = main;
            InitializeComponent();
            InitializeControls();
        }

        private void HomeContent_Load(object sender, EventArgs e)
        {
            this.nScrollingText1.Text = "欢迎使用凌云开发助手，自2016年4月发布正式1.0版以来经历了4个重大版本的升级，详细见开源地址：https://gitee.com/sqlorm/DevelopAssistant。BY 凌云工作室 QQ 270885204";
            //this.nScrollingText1.Text += this.nScrollingText1.Text;
            this.nScrollingText1.ScrollText = this.nScrollingText1.Text;
            this.nScrollingText1.StopScrollOnMouseOver = true;
            this.ScrollingTextBox.Visible = false;

            System.Threading.Tasks.Task.Run(() => {
                System.Threading.Thread.Sleep(2000);
                this.ScrollingTextBox.Invoke(new MethodInvoker(delegate()
                {
                    this.ScrollingTextBox.Visible = true;
                    this.nScrollingText1.Visible = true;                
                }));            
            });
             
            DoScheduleTasks((List<TodoManager.TodoDTO>)AppSettings.ScheduleTasks);
        }

        private void InitializeControls()
        {
            this.WorkBench.Title = "今天是 " + DateTime.Now.ToString("MM,dd yyyy") + " " + GetDayOfWeek();
            this.WorkBench.ItemClick += WorkBenchItem_Click;
            this.nPanel1.BorderStyle = ICSharpCode.WinFormsUI.Controls.NBorderStyle.None;
        }

        private void WorkBenchItem_Click(object sender, NWorkbenchEventArgs e)
        {
            try
            {
                TodoManager.TodoDTO todoItem = serviece.GetTodoItem(e.Item.Tag);
                DateTimeItem item = new DateTimeItem();
                item.Id = todoItem.ID.ToString();
                item.Name = todoItem.Name;
                item.Title = todoItem.Title;
                item.Summary = todoItem.Summary;
                item.ResponsiblePerson = todoItem.ResponsiblePerson;
                item.DateTime = todoItem.DateTime.Value;

                Timeliness timeliness = Timeliness.Green;
                //Enum.TryParse(todoItem.Timeliness.Value.ToString(), out timeliness);
                switch (todoItem.Timeliness.Value)
                {
                    case 1:
                        timeliness = Timeliness.Green;
                        break;
                    case 5:
                        timeliness = Timeliness.Dark;
                        break;
                    case 6:
                        timeliness = Timeliness.Black;
                        break;
                }

                item.Timeliness = timeliness;
                item.Description = todoItem.Description;

                var result = new DevelopAssistant.Core.ToolBox.EditTotoForm(mainForm, item).ShowDialog(this);

                mainForm.RefreshScheduleTasks();


            }
            catch (Exception ex)
            {
                DevelopAssistant.Common.NLogger.WriteToLine(ex.Message, "错误", DateTime.Now, ex.Source, ex.StackTrace);
            }
        }

        public void DoScheduleTasks(List<TodoManager.TodoDTO> NewTodoList)
        {
            IsTodoPromped = false;
            todoList = NewTodoList;

            if (todoList != null && todoList.Count > 0)
            {
                WorkBench.Title = "今天是 " + DateTime.Now.ToString("MM,dd yyyy") + " " + GetDayOfWeek();
                WorkBench.Visible = true;
                WorkBench.TodoOpenState = true;

                DoScheduleTimerTick();

                if (ScheduleTimer == null)
                {                  
                    //ScheduleTimer = new Timer(this.Container);
                    ScheduleTimer = new Timer();
                    ScheduleTimer.Interval = 2 * 1000 * 60; //2 * 1000 * 60; //2分钟刷新一次
                    ScheduleTimer.Tick += ScheduleTimer_Tick;
                    ScheduleTimer.Enabled = true;
                }
            }
            else
            {
                WorkBench.Visible = false;
                WorkBench.TodoOpenState = false;

                DoScheduleTimerTick();
            }
        }

        public void SetTheme(string themeName)
        {
            switch (themeName)
            {
                case "Default":
                    ScrollingTextBox.ForeColor = SystemColors.WindowText;
                    ScrollingTextBox.BackColor = SystemColors.Control;
                    nScrollingText1.BackColor = SystemColors.Control;
                    WorkBench.BackColor = SystemColors.Control;                   
                    BackColor = SystemColors.Control;
                    pictureBox1.BackgroundImage = DevelopAssistant.Core.Properties.Resources.close_16px_easyicon;
                    break;
                case "Black":
                    ScrollingTextBox.ForeColor = Color.FromArgb(220,220,220);
                    ScrollingTextBox.BackColor = Color.FromArgb(030, 030, 030);
                    nScrollingText1.BackColor = Color.FromArgb(030, 030, 030);
                    WorkBench.BackColor = Color.FromArgb(030, 030, 030);
                    BackColor = Color.FromArgb(030, 030, 030);
                    pictureBox1.BackgroundImage = DevelopAssistant.Core.Properties.Resources.close_16px_easyicon_black;
                    break;
            }
            WorkBench.SetTheme(themeName);
        }

        private string GetDayOfWeek()
        {
            string chinseWeekDay = "星期一";
            DayOfWeek week = DateTime.Now.DayOfWeek;
            switch (week)
            {
                case DayOfWeek.Sunday:
                    chinseWeekDay = "星期天";
                    break;
                case DayOfWeek.Monday:
                    chinseWeekDay = "星期一";
                    break;
                case DayOfWeek.Tuesday:
                    chinseWeekDay = "星期二";
                    break;
                case DayOfWeek.Wednesday:
                    chinseWeekDay = "星期三";
                    break;
                case DayOfWeek.Thursday:
                    chinseWeekDay = "星期四";
                    break;
                case DayOfWeek.Friday:
                    chinseWeekDay = "星期五";
                    break;
                case DayOfWeek.Saturday:
                    chinseWeekDay = "星期六";
                    break;
            }
            return chinseWeekDay;
        }

        private void DoSimpleTodoPromp()
        {
            if (WorkBench.WorkbenchList != null && WorkBench.WorkbenchList.Count > 0)
            {
                IsTodoPromped = true;
                if (ScheduleTimer != null)
                {
                    ScheduleTimer.Stop();
                }
                
                mainForm.ShowTodoPromp("你有" + WorkBench.WorkbenchList.Count + "个待办事项，请关注系统提示");

                if (ScheduleTimer != null)
                {
                    ScheduleTimer.Dispose();
                    ScheduleTimer = null;
                }                
            }
            else
            {
                mainForm.CloseTodoPromp();
            }                     
        }         

        private void DoScheduleTimerTick()
        {
            if (!IsTodoPromped)
            {
                List<NWorkbenchItem> worklist = new List<NWorkbenchItem>();

                DateTime dateTimeNow = DateTime.Now;

                WorkBench.Invoke(new MethodInvoker(delegate ()
                {
                    WorkBench.WorkbenchList = null;
                }));

                if(todoList !=null)
                {
                    long maxMilliseconds = 10000;
                    foreach (TodoManager.TodoDTO tododto in todoList)
                    {
                        long milliseconds = maxMilliseconds + 1;
                        if (tododto.DateTime.HasValue)
                        {
                            milliseconds = (Convert.ToInt64(tododto.DateTime.Value.ToString("yyMMddHHmmss")) - Convert.ToInt64(dateTimeNow.ToString("yyMMddHHmmss")));
                        }

                        if (tododto.Timeliness < (int)Timeliness.Dark && milliseconds < maxMilliseconds)
                        {
                            worklist.Add(new NWorkbenchItem(tododto.Title, tododto.DateTime.Value) { Tag = tododto.ID.ToString() });
                        }
                    }
                }

                WorkBench.Invoke(new MethodInvoker(delegate ()
                {
                    if(worklist!=null && worklist.Count > 0)
                    {
                        WorkBench.Title = "请您关注：";
                    }
                    WorkBench.WorkbenchList = worklist;
                }));

                DoSimpleTodoPromp();
            }
        }

        private void ScheduleTimer_Tick(object sender, EventArgs e)
        {
            DoScheduleTimerTick();
        }

        private void nScrollingText1_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("explorer.exe", "https://gitee.com/sqlorm/DevelopAssistant");
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            this.nScrollingText1.Visible = false;
            this.ScrollingTextBox.Controls.Remove(nScrollingText1);
            this.nScrollingText1.Dispose();
            this.Controls.Remove(ScrollingTextBox);
        }
    }
}
